﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FSM.Bll;
using FSM.IBll;
using FSM.Model;

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using Util.Config;

namespace FSM.AutoClean
{
    public class CleanJob : IJob
    {
        public static ITbFilePredeleteBll PreDelteBll { get; set; }

        public async Task Execute(IJobExecutionContext context)
        {
            //await Task.FromResult(0);
            //await WriteLog("测试");
            await RunMonitor();
        }

        /// <summary>
        /// 开始监听执行
        /// </summary>
        /// <returns></returns>
        private async Task RunMonitor()
        {
            await Task.FromResult(0);

            var list = PreDelteBll.List(null, null, null, DateTime.Now.AddMinutes(-5), null, false);
            string basePath = AppSettingConfig.GetValue("FolderPath");
            await WriteLog($"待删除文件/文件夹数量：{list.Count}");

            //用于回调进行删除物理文件
            Func<string, int, string> deleteFileFunc = new Func<string, int, string>((path, type) =>
            {
                try
                {
                    if (type == 1)
                    {
                        if (System.IO.Directory.Exists(path))
                        {
                            System.IO.Directory.Delete(path);
                        }
                        //else
                        //{
                        //    throw new Exception("文件夹不存在");
                        //}
                    }
                    else if (type == 2)
                    {
                        if (System.IO.File.Exists(path))
                        {
                            System.IO.File.Delete(path);
                        }
                        //else
                        //{
                        //    throw new Exception("文件不存在");
                        //}
                    }
                    else
                    {
                        throw new Exception("类型异常");
                    }

                    return "";
                }
                catch (Exception ex)
                {
                    return $"{ex.Message}";
                }
            });

            //先删除文件
            foreach (var record in list.Where(p => p.type == 2))
            {
                await DeleteFileOrFolder(basePath, record, deleteFileFunc);
            }

            //再删除文件夹
            foreach (var record in list.Where(p => p.type == 1).OrderByDescending(p => p.create_date))
            {
                await DeleteFileOrFolder(basePath, record, deleteFileFunc);
            }
        }

        /// <summary>
        /// 删除文件或文件夹
        /// </summary>
        /// <param name="basePath">根目录</param>
        /// <param name="record">记录</param>
        /// <param name="callBack">回调删除物理文件的Func</param>
        /// <returns></returns>
        public async Task DeleteFileOrFolder(string basePath, tb_file_predelete record, Func<string,int, string> callBack)
        {
            string path = $"{basePath}\\{record.dir}\\{record.id}";
            try
            {
                bool success = PreDelteBll.DeleteFile(record.id.Value, callBack, path, record.type.Value);
                string result = success ? "成功" : "失败";
                await WriteLog($"{(record.type == 1 ? "文件夹" : "文件 ")} [{path}] 删除{result}");
            }
            catch (Exception ex)
            {
                await WriteLog($"{(record.type == 1 ? "文件夹" : "文件 ")} [{path}] {ex.Message}");
            }
        }

        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="message">日志消息</param>
        /// <returns></returns>
        private async Task WriteLog(string message)
        {
            await Task.FromResult(0);
            Console.WriteLine($"[AutoClean] {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            Console.WriteLine($"{message}");
            Console.WriteLine();
        }
    }
}
